package com.xxjqr.rbac.auth;

import cn.hutool.core.collection.CollUtil;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class DynamicAccessDecisionManager implements AccessDecisionManager {
    /**
     * @param authentication	当前登录用户的信息
     * @param o
     * @param configAttributes	在 DynamicSecurityMetadataSource.getAttributes()中返回的当前请求url所需要的角色列表
     * @返回 void
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        if (CollUtil.isEmpty(configAttributes)) {
            return;
        }
        //遍历当前请求url所需要的角色列表，如果该用户只要具备其中一个角色，就予以通过
        for (ConfigAttribute configAttribute : configAttributes) {
            String needAuthority = configAttribute.getAttribute();
            //遍历当前用户所具备的角色，只要一个角色能够对应上所需角色中的一个，那么予以通过
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("抱歉，您没有访问权限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
